
require("debugtools")

local socket = require("socket")

local host = host or "127.0.0.1"
local port = port or 15260

if arg ~= nil then
	host = arg[1] or host
	port = arg[2] or port
end

printf("Binding to host '%s' and port %d", host, port)

svr = assert(socket.bind(host, port))
local i, p = svr:getsockname()
assert(i, p)
printf("Waiting connection from talker on %s : %s", i, p)
svr:settimeout(0)

local sockets = {svr}
local clients = {}

local function sendToAll( str )
	for sock, _ in pairs(clients) do
		sock:send(str)
	end
end

while true do
	local results = socket.select(sockets)
	for _, sock in ipairs(results) do
		if sock == svr then
			local connect = svr:accept()
			if connect ~= nil then
				table.insert(sockets, connect)
				clients[connect] = #sockets
				connect:settimeout(0)
				local ip, port = connect:getpeername()
				printf("%s:%s connected", ip, port)
			end

		else
			local ip, port = sock:getpeername()
			local data, err = sock:receive()
			if data ~= nil then
				printf("-- receive: [%s:%s] %s", ip, port, data)
				sendToAll(data)
			elseif err == "closed" then
				table.remove(sockets, clients[sock])
				clients[sock] = nil
				printf("-- closed: %s:%s", ip, port)
			end
		end
	end
end